package tabletask

import (
	"cvevulner/cve-timed-task/db_models"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
)

// DeleteYamlData delete yaml data
func DeleteYamlData(ormModel orm.Ormer) {
	packagesData, rowsAffected, err := db_models.SelectOpenEulerYamlData(ormModel)
	if err != nil {
		logs.Error("db_models.SelectOpenEulerYamlData error:", err.Error())
		return
	}
	if rowsAffected > 0 {
		for _, v := range packagesData {
			if v.PackageId >= 10000000 {
				_, errg := db_models.SelectGaussYamlOriginData(v.PackageName, v.Version, ormModel)
				_, errm := db_models.SelectMindSporeYamlOriginData(v.PackageName, v.Version, ormModel)
				_, erro := db_models.SelectOpenLookengYamlOriginData(v.PackageName, v.Version, ormModel)
				if errors.Is(orm.ErrNoRows, errg) && errors.Is(orm.ErrNoRows, errm) && errors.Is(orm.ErrNoRows, erro) {
					logs.Info("ID of the currently deleted data: ", v.GitId)
					//open transaction
					tranErr := ormModel.Begin()
					if tranErr != nil {
						logs.Error(" Open transaction error:", tranErr.Error())
						continue
					}
					err = db_models.DeleteYamlOpenEulerDetailData(v.GitId, ormModel)
					if err != nil {
						tranErr = ormModel.Rollback()
						if tranErr != nil {
							logs.Error(" Rollback transaction error:", tranErr.Error())
						}
						continue
					}
					err = db_models.DeleteYamlOpenEulerData(v.GitId, ormModel)
					if err != nil {
						tranErr = ormModel.Rollback()
						if tranErr != nil {
							logs.Error(" Rollback transaction error:", tranErr.Error())
						}
						continue
					}
					tranErr = ormModel.Commit()
					if tranErr != nil {
						logs.Error(" Commit transaction error:", tranErr.Error())
						continue
					}
				} else {
					if errg != nil && errors.Is(orm.ErrNoRows, errg) {
						logs.Error("db_models.SelectGaussYamlOriginData: ", errg, v.PackageName, v.Version)
					}
					if errm != nil && errors.Is(orm.ErrNoRows, errm) {
						logs.Error("db_models.SelectMindSporeYamlOriginData: ", errm, v.PackageName, v.Version)
					}
					if erro != nil && errors.Is(orm.ErrNoRows, erro) {
						logs.Error("db_models.SelectOpenLookengYamlOriginData: ", erro, v.PackageName, v.Version)
					}
				}
			}
		}
	}
}
